<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
    <el-card class="login-container">
        <template #header>
            <div class="login-header">
                <h2>用户登录</h2>
            </div>
        </template>

        <el-form ref="loginForm" :model="formData" status-icon label-width="80px" class="login-form" @submit.native.prevent="handleLogin">
            <el-form-item label="用户名" prop="username" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
                <el-input v-model="formData.username" placeholder="请输入用户名" clearable></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
                <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password></el-input>
            </el-form-item>
            <el-form-item><el-checkbox v-model="rememberMe">记住我（7天）</el-checkbox>
            </el-form-item>
            <el-form-item class="form-actions">
                <el-button type="primary" native-type="submit" :loading="loading">立即登录</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
            <div class="login-footer"><el-alert v-if="errorMessage" :title="errorMessage" type="error" show-icon :closable="false"></el-alert>
                <div class="register-link">
                    <span>没有账号？</span>
                    <el-link type="primary" href="register.html">立即注册</el-link>
                </div>
            </div>
        </el-form>
    </el-card>

    <div class="forgot-password">
        <el-link type="danger" @click="showForgotDialog">忘记密码？</el-link>
    </div>

    <!-- 忘记密码对话框 -->
    <el-dialog
            title="密码重置流程"
            :visible.sync="forgotDialogVisible"
            width="30%"
            :close-on-click-modal="false">

        <!-- 第一步：输入用户名 -->
        <el-form v-if="resetStep === 1" ref="forgotForm1" :model="forgotForm" label-width="80px">
            <el-form-item
                    label="用户名"
                    prop="username"
                    :rules="[{ required: true, message: '请输入注册用户名', trigger: 'blur' }]">
                <el-input v-model="forgotForm.username" placeholder="请输入您的注册用户名"></el-input>
            </el-form-item>

            <div class="dialog-footer">
                <el-button @click="forgotDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSendCode">发送验证码</el-button>
            </div>
        </el-form>

        <!-- 第二步：输入验证码和新密码 -->
        <el-form v-if="resetStep === 2" ref="forgotForm2" :model="forgotForm" label-width="100px">
            <el-form-item
                    label="邮箱验证码"
                    prop="code"
                    :rules="[{ required: true, message: '请输入收到的验证码', trigger: 'blur' }]">
                <el-input v-model="forgotForm.code" placeholder="4位数字验证码"></el-input>
            </el-form-item>
            <el-form-item
                    label="新密码"
                    prop="newPassword"
                    :rules="[{ required: true, message: '请输入新密码', trigger: 'blur' }]">
                <el-input v-model="forgotForm.newPassword" type="password" show-password></el-input>
            </el-form-item>
            <div class="dialog-footer">
                <el-button @click="resetStep = 1">上一步</el-button>
                <el-button type="primary" @click="handleResetPassword">提交重置</el-button>
            </div>
        </el-form>
    </el-dialog>
</div>

<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<script src="js/axios-0.18.0.js"></script>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                formData: {
                    username: '',
                    password: ''
                },
                loading: false,
                errorMessage: '',
                rememberMe: false,
                forgotDialogVisible: false,
                resetStep: 1,
                forgotForm: {
                    username: '',
                    code: '',
                    newPassword: ''
                }
            }
        },
        mounted() {
            this.loadRememberedUser();

        },
        methods: {
            loadRememberedUser() {
                console.log('开始读取Cookie，原始数据:', document.cookie);
                const cookies = document.cookie.split('; ');
                let hasRemembered = false;
                cookies.forEach(cookie => {
                    const [key, ...values] = cookie.split('=');
                    const value = values.join('='); // 处理包含等号的值
                    console.log('处理Cookie项:', { key, value });
                    if (key === 'saved_username') {
                        this.formData.username = decodeURIComponent(value || '');//URLDecoder.decode(value || '',"utf-8")//decodeURIComponent(value || '');
                        hasRemembered = true;
                    }
                    if (key === 'saved_password') {
                        this.formData.password = decodeURIComponent(value || '');
                        hasRemembered = true;
                    }
                });
                if (hasRemembered) {
                    this.rememberMe = true;
                    console.log('自动填充完成，用户名:', this.formData.username);
                }
            },
            handleLogin() {
                this.$refs.loginForm.validate(valid => {
                    if (valid) {
                        this.submitLogin()
                    }
                })
            },
            async submitLogin() {
                try {
                    this.loading = true
                    this.errorMessage = ''

                    const params = new URLSearchParams()
                    params.append('username', this.formData.username)
                    params.append('password', this.formData.password)
                    params.append('remember', this.rememberMe);
                    const response = await axios.post('/MVCDemo/auto/login', params, {
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                    })
                    if (response.data.code === 200) {

                        window.location.href = 'space.html';
                    } else {
                        this.errorMessage = response.data.message || '登录失败，请检查用户名和密码'
                    }
                } catch (error) {
                    console.error('登录请求失败:', error)
                    this.errorMessage = '服务器连接失败，请稍后重试'
                } finally {
                    this.loading = false
                }
            },

            resetForm() {
                this.$refs.loginForm.resetFields()
                this.errorMessage = ''
            },
            showForgotDialog() {
                this.resetStep = 1
                this.forgotDialogVisible = true
                this.$nextTick(() => {
                    if (this.$refs.forgotForm1) this.$refs.forgotForm1.resetFields()
                })
            },

            async handleSendCode() {
                try {
                    const valid = await this.$refs.forgotForm1.validate()
                    if (valid) {
                        const response = await axios.post('/MVCDemo/auto/sendEmail',
                            `username=${this.forgotForm.username}`, {
                                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                            })

                        this.$message({
                            type: response.data.code === 200 ? 'success' : 'error',
                            message: response.data.message
                        })

                        if (response.data.code === 200) {
                            this.resetStep = 2
                            this.$nextTick(() => {
                                this.$refs.forgotForm2 && this.$refs.forgotForm2.clearValidate()
                            })
                        }
                    }
                } catch (error) {
                    this.$message.error('请求失败，请检查网络')
                }
            },

            async handleResetPassword() {
                try {
                    const valid = await this.$refs.forgotForm2.validate()
                    if (valid) {
                        const params = new URLSearchParams()
                        params.append('username', this.forgotForm.username)
                        params.append('password', this.forgotForm.newPassword)
                        params.append('emailCode', this.forgotForm.code)

                        const response = await axios.post('/MVCDemo/auto/updatePassword', params, {
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                        })
//alert(response.data.code);
                        this.$message({
                            type: response.data.code === 200 ? 'success' : 'error',
                            message: response.data.message
                        })

                        if (response.data.code === 200) {
                            this.forgotDialogVisible = false
                            this.forgotForm = { username: '', code: '', newPassword: '' }
                        }
                    }
                } catch (error) {
                    this.$message.error('密码重置请求失败')
                }
            }
        }
    })
</script>
</body>
</html>